﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PropertyChanged;
using AllInOne.Models;
using MessageBox = HandyControl.Controls.MessageBox;
using System.IO;
using Microsoft.Win32;
using System.Threading;
using System.Windows.Threading;
using AllInOne.Entity;
using Newtonsoft.Json;
using System.Collections.ObjectModel;

namespace AllInOne.Menu
{
    /// <summary>
    /// 门卫数据展示
    /// </summary>
    [AddINotifyPropertyChangedInterface]
    public partial class LogisticsCentreWindow : Window
    {
        /// <summary>
        /// 最新入厂车辆
        /// </summary>
        public ToBeWeighed Last_Enter { get; set; } = new ToBeWeighed();
        /// <summary>
        /// 入厂车辆列表
        /// </summary>
        public ObservableCollection<ToBeWeighed> ToBe_Enter { get; set; } = new ObservableCollection<ToBeWeighed>();

        /// <summary>
        /// 最新出厂车辆
        /// </summary>
        public ToBeWeighed Last_Out { get; set; } = new ToBeWeighed();
        /// <summary>
        /// 出厂车辆列表
        /// </summary>
        public ObservableCollection<ToBeWeighed> ToBe_Out { get; set; } = new ObservableCollection<ToBeWeighed>();
        
        /// <summary>
        /// 通过货物分类显示--显示所有的货物
        /// </summary>
        public List<ToBeWeighed> ToBe_Good { get; set; }

        public List<ToBeWeighed> ToBeDelivereds { get; set; }

        /// <summary>
        /// 然后定时展示切换数据
        /// </summary>
        public Dictionary<string, ToBeGoodsName> DicGoodsName { get; set; }
        /// <summary>
        /// 展示此货物下的所有车辆过车信息
        /// </summary>
        public ToBeGoodsName ToBe_DicGoodsName { get; set; } = new ToBeGoodsName();

        //readonly System.Timers.Timer tmrQueryGuardOffice = new System.Timers.Timer();//查询门卫展示数据定时器

        //readonly System.Timers.Timer tmrRoll = new System.Timers.Timer();//按货物动态显示车辆数据

        public LogisticsCentreWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ToBe_Enter = new ObservableCollection<ToBeWeighed>();
            ToBe_Out = new ObservableCollection<ToBeWeighed>();
            DicGoodsName = new Dictionary<string, ToBeGoodsName>();
            ////查询网络是否畅通，如果不通则显示空的数据
            //tmrQueryGuardOffice.Interval = 20000;
            //tmrQueryGuardOffice.AutoReset = true;
            //tmrQueryGuardOffice.Elapsed += new System.Timers.ElapsedEventHandler(TrmQueryGuardOfficeData_Elapsed);
            //tmrQueryGuardOffice.Start();

            DispatcherTimer tmrQueryGuardOffice = new DispatcherTimer();
            tmrQueryGuardOffice.Tick += TrmQueryGuardOfficeData_Elapsed;
            tmrQueryGuardOffice.Interval = new TimeSpan(0, 0, 0, 20, 0);//天，时，分，秒，毫秒
            tmrQueryGuardOffice.Start();

            //定时刷新中间的某种货物下的数据
            DispatcherTimer ShowTimer = new DispatcherTimer();
            ShowTimer.Tick += OnTimeLoadData;
            ShowTimer.Interval = new TimeSpan(0, 0, 0, 8, 0);//天，时，分，秒，毫秒
            ShowTimer.Start();
        }

        private void TrmQueryGuardOfficeData_Elapsed(object sender, EventArgs e)
        {
            try
            {
                string msg = "";
                string date = System.DateTime.Now.Date.ToString();
                date = "2022-04-08";
                List<T_RegisterInfo> result = ServiceWebApi.QueryToGuardOffice(date, out msg);
                if (result != null)
                {
                    List<string> rollList = new List<string>();
                    if (ToBe_Enter != null && ToBe_Enter.Count != 0)
                    {
                        ToBe_Enter.Clear();
                    }
                    if (ToBe_Out != null && ToBe_Out.Count != 0)
                    {
                        ToBe_Out.Clear();
                    }
                    for (int i = 0; i < result.Count; i++)
                    {
                        ToBeWeighed temp = new ToBeWeighed();
                        temp.Id = result[i].Id;
                        temp.RegName = result[i].RegName;
                        temp.Plate = result[i].Plate;
                        temp.GoodsName = result[i].GoodsName;
                        temp.Company= result[i].Company;
                        temp.Receiver = result[i].Revicer;
                        temp.ThisJson = JsonConvert.SerializeObject(result[i]);
                        if (result[i].CardStatus == 1)
                        {
                            temp.EnterOut_Time = result[i].ReceiveTime.ToString("HH:mm");
                            temp.EnterOut_Status = "入厂";
                            ToBe_Enter.Add(temp);
                        }
                        else
                        {
                            temp.EnterOut_Time = result[i].ReturnTime.ToString("HH:mm");
                            temp.EnterOut_Status = "出厂";
                            ToBe_Out.Add(temp);
                        }
                        //数据处理
                        GoodsNameInDic(temp);
                    }

                    //测试-----------------------------
                    for (int j = 0; j < 10; j++)
                    {
                        ToBeWeighed temp = new ToBeWeighed();
                        temp.Id = j;
                        temp.RegName = j.ToString() + "姓名";
                        temp.GoodsName = j.ToString() + "货物";
                        if (j == 0)
                        {
                            temp.Company = j.ToString() + "发货单位发货单位发货单位发货单位发货单位发货单位";
                        }
                        else
                        {
                            temp.Company = j.ToString() + "发货单位";
                        }
                        temp.Receiver = j.ToString() + "收货单位";
                        temp.Plate = j.ToString() + "车牌";
                        temp.EnterOut_Time = "12:49";
                        temp.EnterOut_Status = j % 3 == 1 ? "入厂" : "出厂";
                        ToBe_Enter.Add(temp);
                        ToBe_Out.Add(temp);
                        //数据处理
                        GoodsNameInDic(temp);
                    }

                    //最新一条数据
                    if (ToBe_Enter.Count != 0)
                    {
                        Last_Enter = ToBe_Enter[0];
                        SetWrapHeight(tb_Enter_Company, Last_Enter.Company);
                        SetWrapHeight(tb_Enter_Receiver, Last_Enter.Receiver);
                    }
                    if (ToBe_Out.Count != 0)
                    {
                        Last_Out = ToBe_Out[0];
                        SetWrapHeight(tb_Out_Company, Last_Out.Company);
                        SetWrapHeight(tb_Out_Receiver, Last_Out.Receiver);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 动态设置宽高
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetWrapHeight(TextBlock textBlock, string str)
        {
            try
            {
                if (!string.IsNullOrEmpty(str) && str.Length > 13)
                {
                    textBlock.Height = 96;
                    textBlock.Text = "";
                    textBlock.Inlines.Add(new Run(str.Substring(0, 13)));
                    textBlock.Inlines.Add(new LineBreak());
                    textBlock.Inlines.Add(new Run(str.Substring(13)));

                    //最中间的Margin 修改一下，向下移动一些
                }
                else
                {
                    textBlock.Height = 48;
                }

            }
            catch (Exception ex)
            {
                //
            }
        }

        /// <summary>
        /// 刷新显示的货物信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTimeLoadData(object sender, EventArgs e)
        {
            int index = 0;
            bool flag = false;
            foreach (KeyValuePair<string, ToBeGoodsName> dgn in DicGoodsName)
            {
                //如果是最开始为空，则显示第一个
                if (string.IsNullOrEmpty(ToBe_DicGoodsName.GoodsName))
                {
                    ToBe_DicGoodsName = dgn.Value;
                    break;
                }
                index++;
                if (flag)
                {
                    ToBe_DicGoodsName = dgn.Value;
                    break;
                }
                if (dgn.Key == ToBe_DicGoodsName.GoodsName)
                {
                    //如果是最后一个，则显示第一个
                    if (index == DicGoodsName.Count)
                    {
                        foreach (KeyValuePair<string, ToBeGoodsName> itemSon in DicGoodsName)//获取第一个显示出来
                        {
                            ToBe_DicGoodsName = itemSon.Value;
                            break;
                        }
                    }
                    else
                    {
                        flag = true;
                    }
                }
            }
            //绑定数据
            gridGoodsName.ItemsSource = ToBe_DicGoodsName.EnterOut_ToBeWeighed;
        }
        private void GoodsNameInDic(ToBeWeighed temp)
        {
            string keyGoodsName = temp.GoodsName;
            //每次都进行更新 
            if (DicGoodsName == null)
            {
                DicGoodsName = new Dictionary<string, ToBeGoodsName>();
                ////不存在则添加
                NoExitGoodsNameThenAdd(temp);
            }
            else
            {
                if (DicGoodsName.ContainsKey(temp.GoodsName))
                {
                    //则更新此货物的车辆信息
                    if (DicGoodsName[keyGoodsName].EnterOut_ToBeWeighed != null)
                    {
                        //如果存在则先删除，再更新
                        if (DicGoodsName[keyGoodsName].EnterOut_ToBeWeighed.Exists(s => s.Id == temp.Id))
                        {
                            //找到这个index，因为有可能是原来入厂，后面又出厂了，则需要将量进行修改一下，入厂减1，出厂加1数
                            int index = DicGoodsName[keyGoodsName].EnterOut_ToBeWeighed.FindIndex(s => s.Id == temp.Id);
                            if (index >= 0 && DicGoodsName[keyGoodsName].EnterOut_ToBeWeighed[index].EnterOut_Status != temp.EnterOut_Status)
                            {
                                DicGoodsName[keyGoodsName].TotalEnterCount--;
                                DicGoodsName[keyGoodsName].TotalOutCount++;
                            }
                            DicGoodsName[keyGoodsName].EnterOut_ToBeWeighed.RemoveAll(s => s.Id == temp.Id);
                            DicGoodsName[keyGoodsName].EnterOut_ToBeWeighed.Add(temp);
                        }
                        else
                        {
                            if (temp.EnterOut_Status == "入厂")
                            {
                                DicGoodsName[keyGoodsName].TotalEnterCount++;
                            }
                            else
                            {
                                DicGoodsName[keyGoodsName].TotalOutCount++;
                            }
                            DicGoodsName[keyGoodsName].EnterOut_ToBeWeighed.Add(temp);
                        }
                    }
                    else
                    {
                        DicGoodsName[keyGoodsName].EnterOut_ToBeWeighed = new List<ToBeWeighed>();
                        DicGoodsName[keyGoodsName].EnterOut_ToBeWeighed.Add(temp);
                    }
                }
                else
                {
                    ////不存在则添加
                    NoExitGoodsNameThenAdd(temp);
                }
            }
        }
        /// <summary>
        /// 在以货物名字为字两key的显示列表中，如果不存在此字典，则新增DicGoodsName.Add
        /// </summary>
        /// <param name="temp"></param>
        private void NoExitGoodsNameThenAdd(ToBeWeighed temp)
        {
            ToBeGoodsName toBeGoodsName = new ToBeGoodsName();
            toBeGoodsName.Id = temp.Id;
            toBeGoodsName.GoodsName = temp.GoodsName;
            if (temp.EnterOut_Status == "入厂")
            {
                toBeGoodsName.TotalEnterCount = 1;
            }
            else
            {
                toBeGoodsName.TotalOutCount = 1;
            }
            toBeGoodsName.EnterOut_ToBeWeighed = new List<ToBeWeighed>();
            toBeGoodsName.EnterOut_ToBeWeighed.Add(temp);
            DicGoodsName.Add(temp.GoodsName, toBeGoodsName);
        }

        private void Import(object sender, RoutedEventArgs e)
        {
            ////加载数据
            //LoadData();

            //定时将数据区域滚动

            TrmQueryGuardOfficeData_Elapsed(null, null);

            //测试
            //GoodsNameInDic(result[i]);
        }

        private void LoadData()
        {
            #region 初始化公待称重信息
            //ToBeWeigheds = new List<ToBeWeighed>();
            //ToBeDelivereds = new List<ToBeWeighed>();
            //for (int i = 0; i < 5; i++)
            //{
            //    ToBeWeighed temp = new ToBeWeighed();
            //    temp.Index = i + 1;
            //    temp.Name = "王利鹏" + (i + 1).ToString();
            //    temp.Plate = "车牌号" + (i + 1).ToString();
            //    temp.ReciveTime = System.DateTime.Now.ToString("MM-dd HH:mm");
            //    ToBeWeigheds.Add(temp);
            //    ToBeDelivereds.Add(temp);
            //}

            //cb_company.ItemsSource = dl;
            //cb_company.DisplayMemberPath = "value";
            //cb_company.SelectedValuePath = "guid";
            #endregion
        }

    }
}
